<template>
    <div class="app-container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2>项目邀请</h2>
            <div class="header-stats">
                <el-tag type="warning">待处理 {{ getPendingCount() }}</el-tag>
                <el-tag type="success">已接受 {{ getAcceptedCount() }}</el-tag>
                <el-tag type="info">已拒绝 {{ getRejectedCount() }}</el-tag>
                <el-tag type="danger">已过期 {{ getExpiredCount() }}</el-tag>
            </div>
        </div>

        <!-- 搜索筛选 -->
        <el-card class="search-card" shadow="never">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input v-model="searchForm.title" placeholder="搜索项目名称" prefix-icon="el-icon-search" clearable
                        @keyup.enter.native="handleSearch" />
                </el-col>
                <el-col :span="6">
                    <el-select v-model="searchForm.status" placeholder="邀请状态" clearable style="width: 100%">
                        <el-option label="待处理" :value="0" />
                        <el-option label="已接受" :value="1" />
                        <el-option label="已拒绝" :value="2" />
                        <el-option label="已过期" :value="3" />
                    </el-select>
                </el-col>
                <el-col :span="10">
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-card>

        <!-- 邀请表格 -->
        <el-table v-loading="loading" :data="invitationList" element-loading-text="加载中..." border fit
            highlight-current-row style="width: 100%">
            <el-table-column label="项目信息" min-width="300" align="left">
                <template slot-scope="{row}">
                    <div class="project-info-cell">
                        <div class="project-title">{{ row.title }}</div>
                        <div class="project-desc">{{ row.description }}</div>
                        <div class="project-time">
                            <i class="el-icon-time"></i>
                            {{ row.startDate | parseTime('{y}-{m}-{d}') }} 至 {{ row.endDate |
                                parseTime('{y}-{m}-{d}') }}
                        </div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="邀请教师" width="120" align="center">
                <template slot-scope="{row}">
                    <div class="teacher-info">
                        <div class="teacher-name">{{ row.inviteName || row.teacherName }}</div>
                        <div class="teacher-title">教师</div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="邀请时间" width="150" align="center">
                <template slot-scope="{row}">
                    <div>{{ row.createTime | parseTime('{y}-{m}-{d}') }}</div>
                    <div style="color: #909399; font-size: 12px;">{{ row.createTime | parseTime('{h}:{i}') }}</div>
                </template>
            </el-table-column>

            <el-table-column label="邀请消息" min-width="200" align="left">
                <template slot-scope="{row}">
                    <div class="invite-message">
                        {{ row.inviteMessage || '邀请您参与该科研项目' }}
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="状态" width="100" align="center">
                <template slot-scope="{row}">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusText(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="200" align="center" fixed="right">
                <template slot-scope="{row}">
                    <div v-if="row.status === 0">
                        <el-button type="success" size="mini" @click="handleAccept(row)" :loading="row.accepting">
                            接受邀请
                        </el-button>
                        <el-button type="danger" size="mini" @click="handleReject(row)" :loading="row.rejecting">
                            拒绝邀请
                        </el-button>
                    </div>
                    <div v-else-if="row.status === 1">
                        <el-button type="primary" size="mini" @click="handleViewProject(row)">
                            查看项目
                        </el-button>
                    </div>
                    <div v-else-if="row.status === 2">
                        <span style="color: #909399; font-size: 12px;">已拒绝</span>
                    </div>
                    <div v-else-if="row.status === 3">
                        <span style="color: #F56C6C; font-size: 12px;">已过期</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>


        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="total > 0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pagination.pageNo" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>

        <!-- 接受邀请确认对话框 -->
        <el-dialog title="接受项目邀请" :visible.sync="acceptDialogVisible" width="500px" @close="handleCloseAcceptDialog">
            <div v-if="currentInvitation">
                <div class="invitation-detail">
                    <h4>{{ currentInvitation.title }}</h4>
                    <p class="project-description">{{ currentInvitation.description }}</p>
                    <div class="invitation-info">
                        <div class="info-item">
                            <span class="label">邀请教师：</span>
                            <span class="value">{{ currentInvitation.inviteName || currentInvitation.teacherName
                            }}</span>
                        </div>
                        <div class="info-item">
                            <span class="label">项目时间：</span>
                            <span class="value">
                                {{ currentInvitation.startDate | parseTime('{y}-{m}-{d}') }} 至
                                {{ currentInvitation.endDate | parseTime('{y}-{m}-{d}') }}
                            </span>
                        </div>
                        <div class="info-item" v-if="currentInvitation.inviteMessage">
                            <span class="label">邀请消息：</span>
                            <span class="value">{{ currentInvitation.inviteMessage }}</span>
                        </div>
                    </div>
                </div>
                <div class="accept-note">
                    <el-alert title="接受邀请后，您将成为该项目的参与成员，可以查看项目详情和参与项目节点任务。" type="info" :closable="false" show-icon>
                    </el-alert>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="acceptDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAccept" :loading="accepting">确认接受</el-button>
            </div>
        </el-dialog>

        <!-- 拒绝邀请确认对话框 -->
        <el-dialog title="拒绝项目邀请" :visible.sync="rejectDialogVisible" width="500px" @close="handleCloseRejectDialog">
            <div v-if="currentInvitation">
                <div class="invitation-detail">
                    <h4>{{ currentInvitation.title }}</h4>
                    <p class="project-description">{{ currentInvitation.description }}</p>
                </div>
                <div class="reject-reason">
                    <el-form :model="rejectForm" label-width="80px">
                        <el-form-item label="拒绝原因">
                            <el-input v-model="rejectForm.reason" type="textarea" :rows="3" placeholder="请输入拒绝原因（可选）"
                                maxlength="200" show-word-limit>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="reject-note">
                    <el-alert title="拒绝邀请后，该邀请将被标记为已拒绝状态。" type="warning" :closable="false" show-icon>
                    </el-alert>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="rejectDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmReject" :loading="rejecting">确认拒绝</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getStudentInvitations, acceptInvitation, rejectInvitation } from '@/api/research'

export default {
    name: 'ProjectInvitations',
    filters: {
        parseTime
    },
    data() {
        return {
            loading: false,
            searchForm: {
                title: '',
                status: null
            },
            pagination: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            invitationList: [],
            acceptDialogVisible: false,
            rejectDialogVisible: false,
            currentInvitation: null,
            accepting: false,
            rejecting: false,
            rejectForm: {
                reason: ''
            }
        }
    },
    created() {
        this.loadInvitations()
    },
    methods: {
        // 加载邀请列表
        loadInvitations() {
            this.loading = true

            getStudentInvitations({
                ...this.searchForm,
                ...this.pagination
            }).then(response => {
                this.invitationList = response.data.records
                this.total = response.data.total
                this.loading = false
            }).catch(() => {
                // 模拟数据
                setTimeout(() => {
                    this.invitationList = [
                        {
                            invitationId: 1,
                            projectId: 1,
                            title: '深度学习图像识别研究',
                            description: '研究深度学习在图像识别领域的应用，包括CNN、目标检测等技术',
                            startDate: '2025-09-01',
                            endDate: '2026-06-30',
                            teacherName: '张教授',
                            inviteName: '张教授',
                            createTime: '2025-10-25 14:30:00',
                            inviteMessage: '邀请您参与深度学习图像识别研究项目，期待您的加入！',
                            status: 0 // 0-待处理, 1-已接受, 2-已拒绝, 3-已过期
                        },
                        {
                            invitationId: 2,
                            projectId: 2,
                            title: '自然语言处理技术研究',
                            description: '研究最新的自然语言处理技术，包括大语言模型的应用',
                            startDate: '2025-11-01',
                            endDate: '2026-08-31',
                            teacherName: '李教授',
                            inviteName: '李教授',
                            createTime: '2025-10-26 09:15:00',
                            inviteMessage: '希望您能参与我们的自然语言处理研究项目',
                            status: 0
                        },
                        {
                            invitationId: 3,
                            projectId: 3,
                            title: '区块链供应链应用',
                            description: '研究区块链技术在供应链管理中的实际应用',
                            startDate: '2025-08-01',
                            endDate: '2025-12-31',
                            teacherName: '王教授',
                            inviteName: '王教授',
                            createTime: '2025-10-20 16:45:00',
                            inviteMessage: '',
                            status: 1
                        },
                        {
                            invitationId: 4,
                            projectId: 4,
                            title: '机器学习算法优化',
                            description: '研究机器学习算法的优化方法和性能提升',
                            startDate: '2025-09-15',
                            endDate: '2026-03-15',
                            teacherName: '赵教授',
                            inviteName: '赵教授',
                            createTime: '2025-10-18 11:20:00',
                            inviteMessage: '项目时间冲突，暂时无法参与',
                            status: 2
                        },
                        {
                            invitationId: 5,
                            projectId: 5,
                            title: '人工智能伦理研究',
                            description: '研究人工智能技术的伦理问题和社会影响',
                            startDate: '2025-08-01',
                            endDate: '2025-10-01',
                            teacherName: '陈教授',
                            inviteName: '陈教授',
                            createTime: '2025-09-15 10:00:00',
                            inviteMessage: '邀请参与AI伦理研究',
                            status: 3
                        }
                    ]

                    this.total = this.invitationList.length
                    this.loading = false
                }, 1000)
            })
        },

        // 搜索
        handleSearch() {
            this.pagination.pageNo = 1
            this.loadInvitations()
        },

        // 重置搜索
        handleReset() {
            this.searchForm = {
                title: '',
                status: null
            }
            this.handleSearch()
        },

        // 分页
        handleSizeChange(size) {
            this.pagination.pageSize = size
            this.loadInvitations()
        },

        handleCurrentChange(page) {
            this.pagination.pageNo = page
            this.loadInvitations()
        },

        // 接受邀请
        handleAccept(invitation) {
            this.currentInvitation = invitation
            this.acceptDialogVisible = true
        },

        async confirmAccept() {
            this.accepting = true
            try {
                await acceptInvitation(this.currentInvitation.invitationId)
                this.$message.success('已接受项目邀请')
                this.acceptDialogVisible = false
                this.loadInvitations()
            } catch (error) {
                console.error('接受邀请失败:', error)
                this.$message.error('接受邀请失败，请重试')
            } finally {
                this.accepting = false
            }
        },

        handleCloseAcceptDialog() {
            this.currentInvitation = null
        },

        // 拒绝邀请
        handleReject(invitation) {
            this.currentInvitation = invitation
            this.rejectForm.reason = ''
            this.rejectDialogVisible = true
        },

        async confirmReject() {
            this.rejecting = true
            try {
                await rejectInvitation(this.currentInvitation.invitationId, {
                    reason: this.rejectForm.reason
                })
                this.$message.success('已拒绝项目邀请')
                this.rejectDialogVisible = false
                this.loadInvitations()
            } catch (error) {
                console.error('拒绝邀请失败:', error)
                this.$message.error('拒绝邀请失败，请重试')
            } finally {
                this.rejecting = false
            }
        },

        handleCloseRejectDialog() {
            this.currentInvitation = null
            this.rejectForm.reason = ''
        },

        // 查看项目
        handleViewProject(invitation) {
            this.$router.push(`/research/student-detail/${invitation.projectId}`)
        },

        // 工具方法
        getStatusType(status) {
            const types = { 0: 'warning', 1: 'success', 2: 'info', 3: 'danger' }
            return types[status] || 'info'
        },

        getStatusText(status) {
            const texts = { 0: '待处理', 1: '已接受', 2: '已拒绝', 3: '已过期' }
            return texts[status] || '未知'
        },

        getPendingCount() {
            return this.invitationList.filter(item => item.status === 0).length
        },

        getAcceptedCount() {
            return this.invitationList.filter(item => item.status === 1).length
        },

        getRejectedCount() {
            return this.invitationList.filter(item => item.status === 2).length
        },

        getExpiredCount() {
            return this.invitationList.filter(item => item.status === 3).length
        }
    }
}
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

.header-stats {
    display: flex;
    gap: 12px;
}

.search-card {
    margin-bottom: 20px;
    border: 1px solid #EBEEF5;
}

.project-info-cell {
    text-align: left;
}

.project-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 6px;
    line-height: 1.4;
}

.project-desc {
    color: #606266;
    font-size: 13px;
    line-height: 1.4;
    margin-bottom: 6px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.project-time {
    color: #909399;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.teacher-info {
    text-align: center;
}

.teacher-name {
    font-weight: 600;
    color: #303133;
    margin-bottom: 2px;
}

.teacher-title {
    color: #909399;
    font-size: 12px;
}

.invite-message {
    color: #606266;
    font-size: 13px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}


.pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

/* 对话框样式 */
.invitation-detail h4 {
    margin: 0 0 12px 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
}

.project-description {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 16px;
}

.invitation-info {
    margin-bottom: 20px;
}

.info-item {
    display: flex;
    margin-bottom: 8px;
    font-size: 14px;
}

.info-item .label {
    color: #909399;
    width: 80px;
    flex-shrink: 0;
}

.info-item .value {
    color: #303133;
    flex: 1;
}

.accept-note,
.reject-note {
    margin-top: 20px;
}

.reject-reason {
    margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }

    .header-stats {
        width: 100%;
        justify-content: flex-start;
    }
}
</style>
